package cn.ml.duoXianCheng.可见性;

public class C3_线程安全_有序性 {

    public static void main(String[] args) {
        for (int i = 1; i < 500000; i++) {
            C3_线程安全_有序性.State state = new C3_线程安全_有序性.State();
            ThreadA threadA=new ThreadA(state);
            ThreadB threadB=new ThreadB(state);
            threadA.start();
            threadB.start();
            System.out.print("第"+i+"次\t");
        }
    }

    static class ThreadA extends Thread{
        private final C3_线程安全_有序性.State state;
        ThreadA(C3_线程安全_有序性.State state){ this.state = state;}
        public void  run(){
            state.a = 1;
            state.b = 1;
            state.c = 1;
            state.d = 1;
        }
    }
    static class ThreadB extends Thread{
        private final C3_线程安全_有序性.State state;
        public ThreadB(C3_线程安全_有序性.State state) { this.state = state; }
        public void run(){
            //线程ThreadA初始化a,b,c,d时的顺序不同出现下方情况
            //先初始化了b=1，后初始化a=1
            if (state.b==1 && state.a==0 ){
                System.out.println("b==1");
            }
            //先初始化了=1，后初始化a=1,b=1
            if (state.c==1 && (state.b==0 || state.a==0 )){
                System.out.println("c==1");
            }
            //先初始化了d=1，后初始化a=1,b=1,c=1
            if (state.d==1 &&(state.a==0 || state.b==0 || state.c==0 )){
                System.out.println("d==1");
            }
        }
    }

    /*static class State{
        public int a = 0;
        public int b = 0;
        public int c = 0;
        public int d = 0;
    }*/
    static class State{
        public volatile int a = 0;
        public volatile int b = 0;
        public volatile int c = 0;
        public volatile int d = 0;
    }

}
